package com.wlyuan.open.application.service;

import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.excel.util.StringUtils;
import com.wlyuan.open.api.IOpenQrCodeService;
import com.wlyuan.open.application.translator.OpenQrCodeTranslator;
import com.wlyuan.open.core.exception.OpenClientNotFoundException;
import com.wlyuan.open.core.exception.QrcodeExpireException;
import com.wlyuan.open.domain.client.service.OpenClientService;
import com.wlyuan.open.domain.qrcode.service.QrCodeService;
import com.wlyuan.open.vo.OpenQrCodeDetailVO;
import com.wlyuan.open.vo.OpenQrCodeVO;
import com.wlyuan.open.vo.OpenQrCodeValidateVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.Optional;

/**
 * @author lijing
 */
@DubboService
@Slf4j
@RequiredArgsConstructor
public class OpenQrcodeServiceImpl implements IOpenQrCodeService {
    private final QrCodeService qrCodeService;
    private final OpenClientService openClientService;

    @Override
    public OpenQrCodeDetailVO getQrcode(String appId) {
        var qrCodeDetail = qrCodeService.generateQrCode(appId);
        return OpenQrCodeTranslator.translate(qrCodeDetail);
    }

    @Override
    public OpenQrCodeVO check(String qrCodeId) {
        var qrCode = qrCodeService.check(qrCodeId);
        return OpenQrCodeTranslator.translate(qrCode);
    }

    @Override
    public OpenQrCodeValidateVO getQrCodeValue(String qrCodeId) {
        var appId = qrCodeService.getQrCodeValue(qrCodeId);
        if (StringUtils.isBlank(appId)) {
            throw new QrcodeExpireException();
        }
        return Optional.ofNullable(openClientService.ofAppId(appId)).map(client -> {
            OpenQrCodeValidateVO openQrCodeValidateVO = new OpenQrCodeValidateVO();
            openQrCodeValidateVO.setMobile(DesensitizedUtil.mobilePhone(client.getMobile()));
            return openQrCodeValidateVO;
        }).orElseThrow(OpenClientNotFoundException::new);
    }
}
